<?php
require_once("util/DButil.php");
// 获取当前登录的用户id
$uid = $_SESSION["user"]["u_id"];
// 获取购物车
$cart = $_SESSION["cart"];

// 通过事务 保证订单的业务
$conn = getConn();
mysqli_query($conn, "begin");


// 查询序号, 生成订单编号
$time = time();
$day = date("Ymd", $time);
$sql = "select lpad(count(1)+1, 5, '0') num from t_order where o_no like 'SHOP{$day}%' ";


$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);

$index = $row["num"];
$no = "SHOP" . date("YmdHis", $time) . $index;

$num = 0;
$total = 0;
foreach ($cart as $p) {
    $num = $num + $p["num"];
    $total = $total + $p["total"];
}

$sql = "insert into t_order (o_no,o_num,o_total,u_id) values "
." ('{$no}',{$num},{$total}, {$uid})";
// 添加订单并获取返回的订单id标识
$oid = insertReturnKey($conn, $sql);
if(!$oid){
    // order insert 失败
    mysqli_query($conn, "rollback");
    mysqli_close($conn);
    header("location:http://localhost/shop/shopcart.php?msg=order_insert_失败");
    return;
}

$success = true;
// 添加订单详情
foreach ($cart as $p) {
    $sql = "insert into t_detail (o_id,p_id,d_price,d_num,d_total) values"
    ." ($oid, ". $p["p_id"] .", ". $p["p_price"] 
    .", ". $p["num"] .", ". $p["total"] .")";

    $result = mysqli_query($conn, $sql);
    if(!$result){
        // echo mysqli_error($conn);
        // echo "<br>";
        // 只要有一个详情添加失败
        $success = false;
    }
}

if($success){
    // 下单成功后, 清空购物车
    $_SESSION["cart"] = [];
    mysqli_query($conn, "commit");
    mysqli_close($conn);
    // 跳转订单查询页面
    header("location:http://localhost/shop/myOrder.php");
} else {
    // 下单失败, 撤销操作, 跳转购物车
    mysqli_query($conn, "rollback");
    mysqli_close($conn);
    header("location:http://localhost/shop/shopcart.php?msg=下单失败");
}

?>